<template>
    <div class="write">
       <write-header></write-header>
       <TinymceEditor @getTitle="getArticleTitle"></TinymceEditor>
       <div class="bottom">
            <div class="item">
               <span style="color: red;">* </span> 文章标签 
               <el-tag
                v-for="tag in selectTag"
                :key="tag.name"
                closable
                @close="handleClose(tag)"
                :type="tag.type">
                {{tag.name}}
                </el-tag>
               <button class="addTag" @click="showTag = true">+ 添加文章标签</button>
               <div class="tags" v-show="showTag">
                    <div class="head">标签
                        <div class="close" @click="showTag = false">×</div>
                    </div>
                    <el-divider></el-divider>
                    <el-tabs tab-position="left" style="height: 170px;">
                        <el-tab-pane v-for="tag in tags" :key="tag.label" :label="tag.label">
                            <span class="tagItem" v-for="item in tag.tag" :key="item.name" @click="addTags(item)">{{ item.name }}</span>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="tags-bottom">还可以添加{{ 3 - selectTag.length }}个标签</div>
               </div>
            </div>
            <div class="item">
                <span class="text-upload">&nbsp;&nbsp;添加封面 </span> 
                <el-upload
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                >
                    <el-image
                    class="avatar"
                    :src="imageUrl"
                    v-if="imageUrl"
                    fit="contain"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </div>
            <el-button type="primary" round @click="publishArticle">立即发布</el-button>
       </div>
    </div>
</template>

<script>
import WriteHeader from '@/components/WriteHeader.vue'
import { uploadArticle } from '@/api'
export default {
    components:{
        WriteHeader
    },
    data(){
        return {
            showTag:false,
            tags:[
                {
                    label:'Python',
                    tag:[
                        { name:'python', type: '' },
                        { name:'django', type: '' },
                        { name:'pygame', type: '' },
                        { name:'flask', type: '' },
                        { name:'dash', type: '' }
                    ]
                },
                {
                    label:'Java',
                    tag:[
                        { name:'eclipse', type: '' },
                        { name:'java', type: '' },
                        { name:'tomcat', type: '' },
                        { name:'spring', type: '' },
                        { name:'maven', type: '' },
                    ]
                },
                {
                    label:'前端',
                    tag:[
                        { name:'json', type: '' },
                        { name:'html5', type: '' },
                        { name:'javascript', type: '' },
                        { name:'css', type: '' },
                        { name:'ajax', type: '' },
                    ]
                },
                { 
                    label:'数据结构与算法',
                    tag:[
                        { name:'算法', type: '' },
                        { name:'数据结构', type: '' },
                        { name:'贪心算法', type: '' },
                        { name:'链表', type: '' },
                        { name:'二叉树', type: '' },
                    ]
                }
            ],
            selectTag:[],
            imageUrl: '',
            title:'',
            cover:''
        }
    },
    methods:{
        addTags(item){
            if(this.selectTag.length === 3) return
            let name = item.name
            let type = item.type
            let flag = 0
            this.selectTag.forEach(value => {
                if(value.name === name) flag = 1
            })
            if(flag === 1) return
            let obj = {
                name,
                type
            }
            this.selectTag.push(obj);
            
                
        },
        handleClose(tag) {
            this.selectTag.splice(this.selectTag.indexOf(tag), 1);
        },
        //发布文章
        publishArticle(){
            if(this.$store.state.articleValue === ''){
                this.$message.error('输入不能为空');
            }else if(this.selectTag.length === 0){
                this.$message.error('请添加文章标签');
            }else{
                let htmlContent = this.$store.state.articleValue
                // 创建一个虚拟的 DOM 元素，用于解析 HTML 内容
                var tempElement = document.createElement("div");
                tempElement.innerHTML = htmlContent;
                // 获取所有的 img 标签
                var imgElements = tempElement.getElementsByTagName("img");
                let imgSrc = [];
                for(let i = 0; i < imgElements.length; i++){
                    let src = imgElements[i].getAttribute('src')
                    imgSrc.push(src)
                }
                //创建一个formData对象
                var formData = new FormData();
                // 遍历 Blob 数据数组，将每个 Blob 数据转换为文件并添加到 FormData 中
                async function processImages() {
                    var filePromises = [];
                    for (var i = 0; i < imgSrc.length; i++) {
                        var filePromise = fetch(imgSrc[i])
                            .then(response => response.blob())
                            .then(blobData => {
                                // 创建 File 对象
                                let type = blobData.type
                                return new File([blobData], "image", { type });
                            });
                        filePromises.push(filePromise);
                    }
                    const files = await Promise.all(filePromises);
                    files.forEach(file => {
                        formData.append('images', file);
                    });
                }
                processImages().then(() => {
                    // 继续其他操作或提交 formData 到后端
                    let cover = this.cover
                    let author_id = localStorage.getItem('id')
                    let array = this.selectTag;
                    let tags = []
                    let title = this.title
                    let content = this.$store.state.articleValue
                    formData.append('cover', cover)
                    array.forEach(item => {
                        tags.push(item.name)
                    })
                    formData.append('title', title)
                    formData.append('author_id', author_id)
                    formData.append('tags', tags)
                    formData.append('content', content)
                    uploadArticle(formData).then(res => {
                        console.log(res)
                        this.$message.success('发布成功')
                        setTimeout(() => {
                            this.$store.commit('changeArticleValue', '')
                            this.$router.push('home')
                        },1000)
                    })
                });
            }
        },
        beforeAvatarUpload(file){
            let url = URL.createObjectURL(file)
            this.imageUrl = url
            this.cover = file
        },
        getArticleTitle(value){
            this.title = value
        }
    }
}
</script>

<style lang="less" scoped>
.write{
    background-color: #f5f6f7;
    padding-bottom: 20px;
}
.write-header{
    height: 60px;
}
.bottom{
    width: 80%;
    height: 240px;
    background-color: #FFFFFF;
    border-radius: 6px;
    margin: 20px auto;
    margin-bottom: 0;
    padding: 40px;
    box-sizing: border-box;
    color: #606266;
    font-size: 14px;
    .item{
        margin-bottom: 30px;
        .el-tag {
            margin-left: 10px;
        } 
        .addTag{
            height: 28px;
            background-color: #FFFFFF;
            border: 1px solid #e8e8ee;
            color: #555666;
            padding: 0 8px;
            border-radius: 4px;
            margin-left: 20px;
            outline: none;
        }
        .addTag:hover{
            cursor: pointer;
            color: #267dcc;
            background-color: rgba(38,125,204,.05);
            border-color: rgba(38,125,204,.2);
            
        }
        .tags{
            width: 400px;
            position: absolute;
            background-color: #FFFFFF;
            box-shadow: 0 2px 6px 0 rgba(0,0,0,.1);
            top: 740px;
            .el-divider--horizontal{
                margin: 12px 0;
            }
            .head{
                text-align: center;
        
                font-size: 16px;
                padding-top: 10px;
                font-weight: bold;
                .close{
                    font-size: larger;
                    float: right;
                    margin-right: 10px;
                    cursor: pointer;
                }

            }
            .tagItem{
                display: inline-block;
                padding: 0 8px;
                color: #507999;
                height: 24px;
                border-radius: 2px;
                font-weight: 400;
                line-height: 24px;
                background-color: #ebf2f7;
                cursor: pointer;
                font-size: 13px;
                margin-right: 16px;
                margin-bottom: 10px;
            }
            .tags-bottom{
                text-align: right;
                padding: 15px;
                font-size: 13px;
                color: #999;
            }
            .el-tabs__item .is-left{
                text-align: left;
            }
        }
        .text-upload{
            line-height: 40px;
            vertical-align: top;
            margin-right: 20px;
        }
    }
}
.avatar-uploader{
    width: 150px;
    height: 80px;
    display: inline-block;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    .avatar{
        width: 150px;
        height: 80px;
    }
    /deep/.el-upload{
        width: 100%;
    }
    

}
.avatar-uploader:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 80px;
    line-height: 80px;
    text-align: center;
}
.el-button{
    float: right;
    margin-top: -40px;
}
</style>